package com.yangjun.controller.transactionAnalysis;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.yangjun.dao.impl.waresAnalyse.WaresAnalyseDaoImpl;
import com.yangjun.dao.mybatis2.mapper.transactionAnalysis.SalesAnalysisMapper;
import com.yangjun.entity.waresAnalyse.DayOutRateEntity;
import com.yangjun.entity.waresAnalyse.MonthOutRateEntity;
import com.yangjun.utils.AjaxJson;

@RestController
@RequestMapping("/salesanaysis")
public class SalesAnalysisController {
	
	@Autowired
	public SalesAnalysisMapper mapper;
	
	@Autowired
	WaresAnalyseDaoImpl dao;
	
	
	/**
	 * http://192.168.7.32:8080/salesanaysis/getKsType
	 * @param response
	 * @return
	 */
	 @RequestMapping("/getKsType")
	 @ResponseBody
	 public AjaxJson getKsType(HttpServletResponse response){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 Map<String, Object> attributes = Maps.newHashMap();
	     attributes.put("operation", mapper.getCatnameByType("运营科室"));
	     attributes.put("finance", mapper.getCatnameByType("财务科室"));
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 
	/**
	 * http://192.168.7.32:8080/salesanaysis/getMonthOutQty?ordertype=&outtype=&ordersource=&ksty=&ksvalue=&kpi=new_user_cnt
	 * @param response
	 * @param ordertype
	 * @param outtype
	 * @param ordersource
	 * @param ksty
	 * @param ksvalue
	 * @param kpi
	 * @return
	 */
    @RequestMapping("/getMonthOutQty")
	@ResponseBody
	public AjaxJson getMonthOutQty(HttpServletResponse response,
			@RequestParam(value = "ordertype", required = false) String ordertype,
			@RequestParam(value = "outtype", required = false) String outtype,
			@RequestParam(value = "ordersource", required = false) String ordersource,
			@RequestParam(value = "shopcode", required = false) String shopcode,
			@RequestParam(value = "ksty", required = false) String ksty,
			@RequestParam(value = "ksvalue", required = false) String ksvalue,
			@RequestParam(value = "kpi", required = true) String kpi) {

//	    	t.sales_price_avg, --客单价	sum(sales_price_avg*sales_order_cnt)/sum(sales_order_cnt)
//	    	t.sales_sku_avg, --客品数	sum(sales_sku_avg*sales_order_cnt)/sum(sales_order_cnt)
//	    	t.sales_qty_avg, --客件数	sum(sales_qty_avg*sales_order_cnt)/sum(sales_order_cnt)
//	    	marketingcost_rate--搭配占比	sum(marketingcost)/sum(sales_amount)
//	    	sales_gross_rate--毛利率	sum(sales_gross_amount)/sum(sales_amount)
//	    	net_profit_rate--净利率	sum(net_profit)/sum(sales_amount)
//	    	return_rate--退货率	sum(return_amount)/sum(sales_amount)
//	    	net_new_sales_amount-新客销售
//	    	net_new_sales_amount_rate -新客销售%
//	    	net_old_sales_amount-老客销售
//	    	net_old_sales_amount_rate-老客销售%
//	    	new_user_cnt -新客户数
//	    	new_user_cnt_rate -新客户数%
//	    	old_user_cnt -老客户数
//	    	old_user_cnt_rate -老客户数%
	    	
//	        and to_char(data_date,'yyyy') in (${year})
//	        and ordertype = ${ordertype} <!-- 下单类型:0下单,1出库 -->
//	        and outtype = ${outtype}     <!-- 出库类型:0自主,1代发货 -->
//	        and ordersource in (${ordersource})
//	        <if test="ksty=='facategory1'">  <!--  财务科室 -->
//	        and facategory1 in(${facategory1})
//	        </if>
//	        <if test="ksty=='department'">   <!-- 运营科室 -->
//	        and department in(${department})
//	        </if>
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		try {
			 if(StringUtils.isNotBlank(ksvalue)){
				 ksvalue = java.net.URLDecoder.decode(ksvalue,"utf-8");
			 }

		 } catch (UnsupportedEncodingException e) {
			 e.printStackTrace();
		 }
		AjaxJson j = new AjaxJson();
		Calendar now = Calendar.getInstance();
		now.set(Calendar.DATE, now.get(Calendar.DATE) - 1);
		int year = now.get(Calendar.YEAR);// 今年
		int lastyear = year -1 ;
		int last2year = year -2 ;
		int last3year = year -3 ;
		
		int curmonth = now.get(Calendar.MONTH) + 1;//月份
		String yearArr = lastyear+","+year+","+last2year+","+last3year;
		Integer[] yearsz ={lastyear,year}; 
		Map<String, Object> attributes = Maps.newHashMap();
		HashMap<String, Object> parameterMap = Maps.newHashMap();
		parameterMap.put("ordertype", ordertype);
		parameterMap.put("outtype", outtype);
		parameterMap.put("ordersource", ordersource);
		parameterMap.put("shopcode", shopcode);
		parameterMap.put("ksty", ksty);
		parameterMap.put("ksvalue", ksvalue);
		parameterMap.put("year", yearArr);

		List<MonthOutRateEntity> monthOutRateList = new ArrayList<MonthOutRateEntity>();
		
		/**
		 * 3个参数
		 */
		if ("sales_price_avg".equals(kpi.trim())) { //客单价
			parameterMap.put("kpi", "sales_price_avg");
			parameterMap.put("multip", "sales_order_cnt");
			parameterMap.put("divnum", "sales_order_cnt");
			monthOutRateList = mapper.getMonthOutMultipRate(parameterMap);
		} else if ("sales_sku_avg".equals(kpi.trim())) {//客品数
			parameterMap.put("kpi", "sales_sku_avg");
			parameterMap.put("multip", "sales_order_cnt");
			parameterMap.put("divnum", "sales_order_cnt");
			monthOutRateList = mapper.getMonthOutMultipRate(parameterMap);
		} else if ("sales_qty_avg".equals(kpi.trim())) {//客件数
			parameterMap.put("kpi", "sales_qty_avg");
			parameterMap.put("multip", "sales_order_cnt");
			parameterMap.put("divnum", "sales_order_cnt");
			monthOutRateList = mapper.getMonthOutMultipRate(parameterMap);
			
			/**
			 * 2个参数
			 */
		} else if ("marketingcost_rate".equals(kpi.trim())) {//搭配占比 
			parameterMap.put("kpi", "marketingcost");
			parameterMap.put("divnum", "sales_amount");
			monthOutRateList = mapper.getMonthOutRate(parameterMap);
		}else if("sales_gross_rate".equals(kpi.trim())){ //毛利率
			parameterMap.put("kpi", "sales_gross_amount");
			parameterMap.put("divnum", "sales_amount");
			monthOutRateList = mapper.getMonthOutRate(parameterMap);
		}else if("net_profit_rate".equals(kpi.trim())){ //净利率
			parameterMap.put("kpi", "net_profit");
			parameterMap.put("divnum", "sales_amount");
			monthOutRateList = mapper.getMonthOutRate(parameterMap);
		}else if("return_rate".equals(kpi.trim())){//退货率
			parameterMap.put("kpi", "return_amount");
			parameterMap.put("divnum", "sales_amount");
			monthOutRateList = mapper.getMonthOutRate(parameterMap);
		}else if("net_new_sales_amount_rate".equals(kpi.trim())){//新客销额
			parameterMap.put("kpi", "net_new_sales_amount");
			parameterMap.put("divnum", "sales_amount");
			monthOutRateList = mapper.getMonthOutRate(parameterMap);
		}else if("net_old_sales_amount_rate".equals(kpi.trim())){//老客销额
			parameterMap.put("kpi", "net_old_sales_amount");
			parameterMap.put("divnum", "sales_amount");
			monthOutRateList = mapper.getMonthOutRate(parameterMap);
		}else if("new_user_cnt_rate".equals(kpi.trim())){//新客占比
			parameterMap.put("kpi", "new_user_cnt");
			parameterMap.put("divnum", "new_user_cnt");
			parameterMap.put("add", "old_user_cnt");
			monthOutRateList = mapper.getMonthOutAddRate(parameterMap);
		}else if("old_user_cnt_rate".equals(kpi.trim())){//老客占比
			parameterMap.put("kpi", "old_user_cnt");
			parameterMap.put("divnum", "new_user_cnt");
			parameterMap.put("add", "old_user_cnt");
			monthOutRateList = mapper.getMonthOutAddRate(parameterMap);
		}
		
		else {
			parameterMap.put("kpi", kpi);
			monthOutRateList = mapper.getMonthOutQty(parameterMap);
		}
		attributes.put("monthOutQty", monthOutRateList);
		List<Object> currList = new ArrayList<Object>();
		List<Object> lastList = new ArrayList<Object>();
		String[] months = { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };
		for (MonthOutRateEntity entity : monthOutRateList) {
			if (year == entity.getYear()) {
				currList = dao.getMonthkpiValue(entity,curmonth);
			} else if (lastyear == entity.getYear()){
				lastList = dao.getMonthkpiValue(entity);
			}
		}
		Map<String, Object> directesult = Maps.newHashMap();
		directesult.put("legend", yearsz);
		directesult.put("xAxis", months);
		directesult.put("last_yvalue", lastList);
		directesult.put("curr_yvalue", currList);
		attributes.put("monthOutQtyDirect", directesult);
		j.setAttributes(attributes);
		return j;
	}
    
//    http://192.168.7.32:8080/salesanaysis/getDayOutQty?ordertype=&outtype=&ordersource=&ksty=&ksvalue=&kpi=sales_price_avg
    @RequestMapping("/getDayOutQty")
    @ResponseBody
    public AjaxJson getDayOutQty(HttpServletResponse response,
    		@RequestParam(value = "ordertype", required = false) String ordertype,
    		@RequestParam(value = "outtype", required = false) String outtype,
    		@RequestParam(value = "ordersource", required = false) String ordersource,
    		@RequestParam(value = "shopcode", required = false) String shopcode,
    		@RequestParam(value = "ksty", required = false) String ksty,
    		@RequestParam(value = "ksvalue", required = false) String ksvalue,
    		@RequestParam(value = "kpi", required = true) String kpi) {
    	
    	response.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html;charset=UTF-8");
    	try {
    		if(StringUtils.isNotBlank(ksvalue)){
    			ksvalue = java.net.URLDecoder.decode(ksvalue,"utf-8");
    		}
    		
    	} catch (UnsupportedEncodingException e) {
    		e.printStackTrace();
    	}
    	AjaxJson j = new AjaxJson();
    	Calendar now = Calendar.getInstance();
    	now.set(Calendar.DATE, now.get(Calendar.DATE) - 1);
    	int year = now.get(Calendar.YEAR);// 今年
    	int lastyear = year -1 ;
    	
    	int curday = now.get(Calendar.DATE);//当前日
    	
    	
    	String yearArr = lastyear+","+year;
    	Map<String, Object> attributes = Maps.newHashMap();
    	HashMap<String, Object> parameterMap = Maps.newHashMap();
    	parameterMap.put("ordertype", ordertype);
    	parameterMap.put("outtype", outtype);
    	parameterMap.put("ordersource", ordersource);
    	parameterMap.put("shopcode", shopcode);
    	parameterMap.put("ksty", ksty);
    	parameterMap.put("ksvalue", ksvalue);
    	parameterMap.put("year", yearArr);
    	
    	List<DayOutRateEntity> dayOutQtyList = new ArrayList<DayOutRateEntity>();
    	
    	/**
    	 * 3个参数
    	 */
    	if ("sales_price_avg".equals(kpi.trim())) { //客单价
    		parameterMap.put("kpi", "sales_price_avg");
    		parameterMap.put("multip", "sales_order_cnt");
    		parameterMap.put("divnum", "sales_order_cnt");
    		dayOutQtyList = mapper.getDayOutMultipRate(parameterMap);
    	} else if ("sales_sku_avg".equals(kpi.trim())) {//客品数
    		parameterMap.put("kpi", "sales_sku_avg");
    		parameterMap.put("multip", "sales_order_cnt");
    		parameterMap.put("divnum", "sales_order_cnt");
    		dayOutQtyList = mapper.getDayOutMultipRate(parameterMap);
    	} else if ("sales_qty_avg".equals(kpi.trim())) {//客件数
    		parameterMap.put("kpi", "sales_qty_avg");
    		parameterMap.put("multip", "sales_order_cnt");
    		parameterMap.put("divnum", "sales_order_cnt");
    		dayOutQtyList = mapper.getDayOutMultipRate(parameterMap);
    		
    		/**
    		 * 2个参数
    		 */
    	} else if ("marketingcost_rate".equals(kpi.trim())) {//搭配占比 
    		parameterMap.put("kpi", "marketingcost");
    		parameterMap.put("divnum", "sales_amount");
    		dayOutQtyList = mapper.getDayOutRate(parameterMap);
    	}else if("sales_gross_rate".equals(kpi.trim())){ //毛利率
    		parameterMap.put("kpi", "sales_gross_amount");
    		parameterMap.put("divnum", "sales_amount");
    		dayOutQtyList = mapper.getDayOutRate(parameterMap);
    	}else if("net_profit_rate".equals(kpi.trim())){ //净利率
    		parameterMap.put("kpi", "net_profit");
    		parameterMap.put("divnum", "sales_amount");
    		dayOutQtyList = mapper.getDayOutRate(parameterMap);
    	}else if("return_rate".equals(kpi.trim())){//退货率
    		parameterMap.put("kpi", "return_amount");
    		parameterMap.put("divnum", "sales_amount");
    		dayOutQtyList = mapper.getDayOutRate(parameterMap);
    	}else if("net_new_sales_amount_rate".equals(kpi.trim())){//新客销额
			parameterMap.put("kpi", "net_new_sales_amount");
			parameterMap.put("divnum", "sales_amount");
			dayOutQtyList = mapper.getDayOutRate(parameterMap);
		}else if("net_old_sales_amount_rate".equals(kpi.trim())){//老客销额
			parameterMap.put("kpi", "net_old_sales_amount");
			parameterMap.put("divnum", "sales_amount");
			dayOutQtyList = mapper.getDayOutRate(parameterMap);
		}else if("new_user_cnt_rate".equals(kpi.trim())){//新客占比
			parameterMap.put("kpi", "new_user_cnt");
			parameterMap.put("divnum", "new_user_cnt");
			parameterMap.put("add", "old_user_cnt");
			dayOutQtyList = mapper.getDayOutAddRate(parameterMap);
		}else if("old_user_cnt_rate".equals(kpi.trim())){//老客占比
			parameterMap.put("kpi", "old_user_cnt");
			parameterMap.put("divnum", "new_user_cnt");
			parameterMap.put("add", "old_user_cnt");
			dayOutQtyList = mapper.getDayOutAddRate(parameterMap);
		} else {
    		parameterMap.put("kpi", kpi);
    		dayOutQtyList = mapper.getDayOutQty(parameterMap);
    	}
    	attributes.put("dayOutQty", dayOutQtyList);
		 
		 String[] days = { "01","02","03","04","05","06","07","08","09","10",
		    	   "11","12","13","14","15","16","17","18","19","20",
		    	   "21","22","23","24","25","26","27","28","29","30","31"};
		 
		 List<Object> legend=new ArrayList<Object>();
		 List<Float> currList=new ArrayList<Float>();
		 List<Float> lastList=new ArrayList<Float>();
		 
		 if(dayOutQtyList!=null && dayOutQtyList.size()>=2){
			 DayOutRateEntity curEntity = dayOutQtyList.get(0);
			 DayOutRateEntity lastEntity = dayOutQtyList.get(1);
			 legend.add(lastEntity.getData_mth());
			 legend.add(curEntity.getData_mth());
			 currList = dao.getDaykpiValue(curEntity,curday);
			 lastList = dao.getDaykpiValue(lastEntity);
		 }else if(dayOutQtyList!=null && dayOutQtyList.size()==1){
			 DayOutRateEntity curEntity = dayOutQtyList.get(0);
			 legend.add(curEntity.getData_mth());
			 currList = dao.getDaykpiValue(curEntity,curday);
		 }
		 Map<String,Object> directesult = Maps.newHashMap(); 
		 directesult.put("legend", legend);
		 directesult.put("xAxis", days);
		 directesult.put("last_yvalue", lastList);
		 directesult.put("curr_yvalue", currList);
		 attributes.put("DayOutQtyDirect", directesult);
		 j.setAttributes(attributes);
		 return j;
    }

}
